package com.aifund.app.service.impl;

import com.aifund.app.service.PhoneCodeService;
import com.aifund.common.enums.redis.RedisSetKey;
import com.aifund.common.exception.AiFundException;
import com.aifund.common.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.xml.soap.SAAJResult;

@Service
public class PhoneCodeServiceImpl implements PhoneCodeService {

    //验证码有效时间
    private int phoneCodeTime = 10*60;


    @Autowired
    RedisUtil redisUtil;

    @Override
    public String sendPhoneCode(String phone) {

        Object code = redisUtil.hget(RedisSetKey.PHONE_CODE.getSetKey(), phone);
//        if(code == null){
            String newCode = createRandom(true,6);
            /**
             * 发送验证码业务API调取
             */

            if(!redisUtil.hset(RedisSetKey.PHONE_CODE.getSetKey(),phone,newCode,phoneCodeTime)){
                throw new AiFundException("500","服务器异常","Redis缓存手机验证码失败!");
            }
            return newCode;
//        }else{
//            throw new AiFundException("400","验证码10分钟内有效，请勿重复发送!");
//        }

    }

    @Override
    public String getPhoneCode(String phone) {
        Object code = redisUtil.hget(RedisSetKey.PHONE_CODE.getSetKey(), phone);
        return "null".equals(String.valueOf(code))?null:String.valueOf(code);
    }

    @Override
    public void removePhoneCode(String phone) {
        redisUtil.hdel(RedisSetKey.PHONE_CODE.getSetKey(),phone);
    }

    /**
     * 创建指定数量的随机字符串
     * @param numberFlag 是否是数字
     * @param length
     * @return
     */
    private static String createRandom(boolean numberFlag, int length){
        String retStr = "";
        String strTable = numberFlag ? "1234567890" : "1234567890abcdefghijkmnpqrstuvwxyz";
        int len = strTable.length();
        boolean bDone = true;
        do {
            retStr = "";
            int count = 0;
            for (int i = 0; i < length; i++) {
                double dblR = Math.random() * len;
                int intR = (int) Math.floor(dblR);
                char c = strTable.charAt(intR);
                if (('0' <= c) && (c <= '9')) {
                    count++;
                }
                retStr += strTable.charAt(intR);
            }
            if (count >= 2) {
                bDone = false;
            }
        } while (bDone);

        return retStr;
    }

}
